<?php
/**
 * 模型逻辑处理
 */
namespace plugins\qbt_custom_model\service;
use think\Db;

class FieldService
{
    //拼接添加字段的sql语句，modify不考虑
    //alter table `qbtcmf_article` add `name` varchar(250) not null default '' comment '嘻嘻嘻'
    //alter table `qbtcmf_article` change `oldname` `newname` varchar(250) not null default '' comment '嘻嘻嘻'
    private static $sql = "ALTER TABLE %tabname% %add% %change% %name% %newname% %type%%length% NOT NULL %default% %comment%";

    /**
     * 添加字段
     * @param $data 表单数据
     * @param string $field_type 1增加2修改
     */
    public static function AddField($data,$tabname){
        self::add_modify($data,$tabname,1);
    }
    /**
     * 编辑字段
     * @param $data 表单数据
     * @param string $field_type 1增加2修改
     */
    public static function EditField($data,$tabname,$field_type=2,$oldname=''){
        self::add_modify($data,$tabname,$field_type,$oldname);
    }

    /**
     * 增加
     */
    protected static function add_modify($data,$tabname,$field_type=1,$oldname=''){
        //表名
        $tabname = config("database.prefix").$tabname;
        //添加
        if ($field_type==2){
            $add = '';
            $change = 'CHANGE';
            //字段名
            $name = $oldname;
            //新字段名
            $newname = $data['field_name'];
        }else{
            $add = 'ADD';
            $change = '';
            //新字段名
            $newname = $data['field_name'];
            //字段名
            $name = '';
        }

        //如果是外联的字段后面的将会另作拼接
        if($data['field_type'] == "outreach"){
            $tarr = explode(".",$data['field_outreach']);
            //查询对应表
            $get_field_info = "DESC ".$tarr[0];
            $res = Db::query($get_field_info);
            $ftype = "";
            foreach ($res as $p=>$q){
                if($q['Field'] == $tarr[1]){
                    $ftype = $q['Type'];
                }
            }
            //$default = "DEFAULT '".$data['field_default']."'";
            $comment = "COMMENT '".$data['field_nikename']."'";
            $arr = ['%tabname%','%add%','%change%','%name%','%newname%','%type%','%length%','%default%','%comment%'];
            $rep = [$tabname,$add,$change,$name,$newname,$ftype,"","",$comment];
            $sql = str_replace($arr,$rep,static::$sql);
            //dump($sql);
            Db::query($sql);
            return ;
        }


        //类型
        if(isset($data['field_type2'])){
            $type = $data['field_type2'];
        }else{
            $type = static::get_field_type($data['field_type']);//取出默认
        }
        //长度
        if(isset($data['field_length'])){
            if('float' == $data['field_type']){
                if($data['field_length']!=''&&$data['field_length']!=''){
                    $length = "(".$data['field_length'].",".$data['field_digits'].")";
                }else{
                    $length = '';
                }
                $data['field_default'] = floatval($data['field_default']);
            }else{
                if('' == $data['field_length']){
                    $length = '';
                }else{
                    $length = "(".$data['field_length'].")";
                }
            }
        }else{
            $length = '';
        }

        if($data['field_type'] == 'number' || $data['field_type'] == 'datetime'  || $data['field_type'] == 'radio' || $data['field_type'] == 'select'){
            if(!$data['field_default']) $data['field_default'] = 0;
            //默认值
            $default = "DEFAULT ".$data['field_default'];
        }else{
            //默认值
            $default = "DEFAULT '".$data['field_default']."'";
        }

        //注释
        $comment = "COMMENT '".$data['field_nikename']."'";

        if($type=="varchar"&&$length==''){
            $length = "(255)";
        }

        $arr = ['%tabname%','%add%','%change%','%name%','%newname%','%type%','%length%','%default%','%comment%'];
        $rep = [$tabname,$add,$change,$name,$newname,$type,$length,$default,$comment];
        $sql = str_replace($arr,$rep,static::$sql);
        //dump($sql);
        
        //edit 2019.1.22 liq 判断是否已存在字段
        $table_schema = config("database.database");
        $param = [
            $tabname,
            $table_schema,
            $newname
        ];
        $result = Db :: query("SELECT COLUMN_NAME as field,column_comment as comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ? AND table_schema = ? AND COLUMN_NAME = ?", $param);
        if(!empty($result)){
            return false;
        }
        
        Db::query($sql);
        return true;
    }



    /**
     * 获取默认字段类型
     */
    protected static function get_field_type($field_type){
        $type = "";
        switch ($field_type){
            case 'text':$type = "varchar";break;
            case 'textarea':$type = "text";break;
            case 'html':$type = "text";break;
            case 'radio':$type = "tinyint(3) unsigned";break;
            case 'checkbox':$type = "varchar(1000)";break;
            case 'select':$type = "tinyint(3) unsigned";break;
            case 'image':$type = "varchar(250)";break;
            case 'images':$type = "text";break;
            case 'file':$type = "varchar(250)";break;
            case 'files':$type = "text";break;
            case 'number':$type = "int";break;
            case 'float':$type = "float";break;
            case 'datetime':$type = "int(10) unsigned";break;
            case 'outreach':$type = "";break;
        }
        return $type;
    }
}